<template>
  <div class="webchatMsgItem clearfix">
    <!-- 系统消息 -->
    <div v-if="chatMsg.type === 'system'" class="systemMsg">
      {{(chatMsg.createTime ? chatMsg.createTime : '')  + ' ' + chatMsg.content}}
    </div>
    <!-- 满意度系统消息 -->
    <div v-if="chatMsg.type === 'csrInvite'" class="systemMsg">
      {{(chatMsg.createTime ? chatMsg.createTime : '')  + ' ' + chatMsg.content}}
    </div>
    <!-- 满意度提交系统消息 -->
    <div v-if="chatMsg.type === 'csrSubmit'" class="systemMsg">
      {{(chatMsg.createTime ? chatMsg.createTime : '')  + ' '}}
      <span class="csrSubmit">{{chatMsg.content}}</span>
    </div>
    <!-- 座席撤回系统消息 -->
    <div v-if="chatMsg.type === 'withdrawMsg'" class="systemMsg">
      {{(chatMsg.createTime ? chatMsg.createTime : '')  + ' ' + chatMsg.content}}
      <span v-if="chatMsg.withdrawContentType === 'text'" class="toEdit" @click="toEditFun(chatMsg.withdrawContent, chatMsg.withdrawContentNew)">重新编辑</span>
    </div>
    <!-- 上一条消息和当前消息的sessionId 不一样展示 -->
    <div class="systemMsg historyLine" v-if="chatMsgIndex < messageList.length - 1 && chatMsg.sessionId
       && messageList[chatMsgIndex + 1].sessionId && (chatMsg.sessionId !== messageList[chatMsgIndex + 1].sessionId)">
      <span class="dividedLine"></span>
      <span class="historyText">以上是历史会话消息</span>
      <span class="dividedLine"></span>
    </div>
    <!-- 非系统消息 -->
    <div v-if="!['system', 'csrInvite', 'csrSubmit', 'withdrawMsg'].includes(chatMsg.type)" class="clearfix chatContent" :class="chatMsg.type === 'in' ? 'fl' : 'fr'"
        :style="{width: importType === 'dataCenter' ? 'calc(100% - 30px)' : 'calc(100% - 100px)'}">
      <div class="clearfix">
          <!-- 头像start -->
            <!-- 访客消息头像 -->
        <div v-if="chatMsg.type === 'in'" class="fl visitorsHeadImg">
          <img :src="chatMsg.visitorHeadImg" alt="" class="out" v-if="chatMsg.visitorHeadImg">
          <img src="../../assets/img/visitorsHeadImg.png" alt="" class="out" v-else>
        </div>
          <!-- 座席头像 -->
        <div v-if="chatMsg.type ==='out' && chatMsg.userId !== 'system'" class="fr">
           <!-- 机器人头像是带域名的，座席头像不带域名需要自己拼写 -->
          <img :src="chatMsg.userId === 'robot' ? chatMsg.userHeadImg : common.doMain + chatMsg.userHeadImg" alt=""
            class="systemHeadImg headImg" v-if="chatMsg.userHeadImg && chatMsg.userHeadImg !== '1'">
            <!-- 机器人默认头像 -->
          <img src="../../assets/img/robot-user.png" alt="" v-else-if="chatMsg.userHeadImg && chatMsg.userHeadImg === '1'" class="headImg out">
          <!-- 座席默认头像 -->
          <img src="../../assets/img/userAgent.png" alt="" class="headImg out" v-else>
        </div>
          <!-- 系统消息头像 -->
        <div v-if="chatMsg.type === 'out' && chatMsg.userId === 'system'" class="fr">
          <!-- <img :src="doMain + chatMsg.userHeadImg" alt="" class="systemHeadImg headImg" v-if="chatMsg.userHeadImg"> -->
          <!-- 系统消息默认头像 -->
          <img src="../../assets/img/webchatSystem.png" alt="" class="headImg out">
        </div>
          <!-- 头像end -->
        <!-- 时间 -->
        <div class="time" :class="chatMsg.type === 'in' ? 'fl inTime' : 'fr outTime'">
          <span>{{chatMsg.createTime ? chatMsg.createTime : ''}}</span>
          <span v-if="chatMsg.type === 'out'" class="name">{{outName(chatMsg)}}</span>
        </div>
      </div>
      <!-- 消息内容 -->
      <div :class="chatMsg.type === 'in' ? 'fl inBox' : 'fr outBox'" class="chatContentBox" @mouseenter="disabledFun(chatMsg)">
        <!-- 撤回按钮 -->
        <span class="V7_iconfont V7_iconV7tubiao_chehui" v-show="chatMsg.tipDisabled && (!chatMsg.sendStatus || chatMsg.sendStatus === 'success')"
          @click="withdrawFun(chatMsg)"></span>
        <!-- 消息状态 -->
        <div class="sendStatus fl" v-if="chatMsg.type === 'out' && chatMsg.sendStatus"
            :class="{ success: chatMsg.sendStatus === 'success',  fail: chatMsg.sendStatus === 'fail'}">
        </div>
        <!-- 已读未读状态 -->
        <span v-if="common.globalConfig && common.globalConfig.isVisitorReadMessage &&
          ['pc', 'wap', 'sdk', 'wxsdk'].includes(chatMsg.platform) &&
          chatMsg.type === 'out' && (!chatMsg.sendStatus || chatMsg.sendStatus === 'success')"
          :class="{'V7_iconV7tubiao_danxuan': chatMsg.dealUserMsg,
          'V7_iconV7tubiao_danxuanweixuan': !chatMsg.dealUserMsg}"
          :style="{color: !chatMsg.dealUserMsg ? '#008BEE' : '#A6A6AE'}"
          class="msgStatus V7_iconfont"></span>
        <!-- 微信，小程序错误状态 -->
        <el-tooltip v-if="chatMsg.type === 'out' && chatMsg.errorCode" :content="common.webchatErrorCode[chatMsg.errorCode]" placement="top">
          <div class="fl sendStatus fail"></div>
        </el-tooltip>
        <!-- 纯文本, 机器人分组消息, 机器人物流消息 (contentType, text为文本消息，newPushQues 为机器人分组消息, msgTask 为机器人物流消息)-->
        <div class='chatContentItemBox' :style="chatMsg | handleTextBoxWidth"
          :class="{'outTextBgc fl':  chatMsg.type === 'in', 'inTextBgc fl' : chatMsg.type === 'out', 'isSearchKey': chatMsg.isSearchKey, 'chatContentItemBoxSearch': currentTabType === 'webchat_todo' && chatMsg.type === 'in'}"
          v-if="chatMsg.contentType === 'text' || chatMsg.contentType === 'newPushQues' || chatMsg.contentType === 'msgTask'"
          >
          <div v-html="chatMsg.content"></div>
          <i class="V7_iconfont V7_iconV7tubiao_sousuo search" @click.stop="handleRobotSearch"></i>
        </div>
        <!-- 富文本消息 -->
        <div class="chatContentItemBox" :style="chatMsg | handleTextBoxWidth"
          :class="chatMsg.type === 'in' ? 'outTextBgc fl' : 'inTextBgc fl'"
          v-if="chatMsg.contentType === 'richText'" v-html="chatMsg.content">
        </div>
        <!-- 图片消息 -->
        <div v-if="chatMsg.contentType === 'image'" :style="chatMsg | handleTextBoxWidth" @click="previewImg(chatMsg)" :class="chatMsg.type === 'in' ? 'fl' : 'fr'">
          <webchatBigImage
            class="imageMsg"
            :msgId="chatMsg.createTimestamp + ''"
            :z-index="9999"
            :src="chatMsg.content +'?imageView2/2/w/200/h/200'"
            :preview-src-list="imageUrls">
          </webchatBigImage>
        </div>
        <!-- 语音消息 -->
        <div v-if="chatMsg.contentType === 'voice'" :style="chatMsg | handleTextBoxWidth"
            :class="chatMsg.type === 'in' ? 'outTextBgc fl' : 'fr'" @click="playVoice(chatMsg)">
          <webchatVoice :chatMsg="chatMsg" :sessionId="sessionId"></webchatVoice>
        </div>
        <!-- 微信视频 -->
        <div v-if="chatMsg.contentType === 'video'" @click="playVideo(chatMsg)" class="videoBox">
          <div class="wechat_video_play_icon">
            <div class="play_icon" style="backgroundSize: 100%"></div>
          </div>
          <img v-if="chatMsg.thumbPicUrl" :src="common.imDoMain + chatMsg.thumbPicUrl">
          <div v-else class="videoBoxNoData">
            <div class="thunmbnail_no_icom"></div>
          </div>
        </div>
        <!-- 小程序商品卡片消息 -->
        <div v-if="chatMsg.contentType === 'miniprogrampage'"
          :style="chatMsg | handleTextBoxWidth" class="cardInfo clearfix"
          :class="chatMsg.type === 'in' ? 'fl' : 'fr'">
          <img :src="picUrlHandle(chatMsg.miniCardInfo.pictureUrl)" alt="" class="fl">
          <div class="fl cardInfoLeft" :style="{width: importType === 'dataCenter' ? '130px' : '180px'}">
            <div class="cardInfoTitle">
              {{chatMsg.miniCardInfo.title}}
            </div>
            <div class="cardInfoFlag">
              <span class="V7_iconfont V7_iconV7tubiao_weixinxiaochengxu"></span>
              微信小程序
            </div>
          </div>
        </div>
        <!-- 订单商品卡片消息 -->
        <div v-if="chatMsg.contentType === 'orderCardInfo'"
          :style="chatMsg | handleTextBoxWidth" class="orderCardInfo clearfix"
          :class="chatMsg.type === 'in' ? 'fl' : 'fr'">
          <div>
            <h5>{{chatMsg.content.orderTitle || ''}}</h5>
            <p class="orderNum"><span>{{chatMsg.content.orderNumName || ''}}</span><span>{{chatMsg.content.orderNum || ''}}</span></p>
          </div>
          <template v-if="chatMsg.content.orderList && chatMsg.content.orderList.length > 0">
            <div v-for="(orderListItem, orderListIndex) in chatMsg.content.orderList"
              :key="orderListIndex" class="orderListItem clearfix"
              @click="orderOpen({type: orderListItem.clickTarget || '', url: orderListItem.clickUrl || ''})">
              <img :src="orderListItem.imgUrl || ''" alt="" class="fl">
              <div class="fl orderRight">
                <div class="orderRightTitle">{{orderListItem.content || ''}}</div>
                <div class="orderPrice">{{orderListItem.price || ''}}</div>
              </div>
            </div>
          </template>
          <div v-if="chatMsg.content.btnRightShow" class="orderBtn fr"
            @click="orderOpen({type: chatMsg.content.btnRightTarget || '', url: chatMsg.content.btnRightUrl || ''})">
            {{chatMsg.content.btnRightText}}
          </div>
          <div v-if="chatMsg.content.btnLeftShow" class="orderBtn fr" style="marginRight: 10px"
            @click="orderOpen({type: chatMsg.content.btnLeftTarget || '', url: chatMsg.content.btnLeftUrl || ''})">
            {{chatMsg.content.btnLeftText}}
          </div>
        </div>
        <!-- 文件消息 -->
        <div v-if="chatMsg.contentType === 'file'" class="fileMsg clearfix" :class="chatMsg.type === 'in' ? 'fl' : 'fr'">
          <div class="fileProess" :style="{width: chatMsg.percent + '%'}" v-show="chatMsg.percent && chatMsg.percent !== 100"></div>
          <div class="clearfix">
            <!-- <icon-svg class="fl fileIcon" :iconClass="chatMsg | fileIcon"></icon-svg> -->
            <div class="fl fileIcon" v-fileSvg="[chatMsg.fileName, 36]"></div>
            <div class="fl">
              <p class="fileName">{{chatMsg.fileName}}</p>
              <p class="fileSize">{{chatMsg.fileSize}}
                <span>/</span>
                <!-- pdf用a链接是新tab打开，若里面存在xss文件，则会被执行，若用插件的模式，mp4无法解析，所以单独先处理下pdf类型的 -->
                <span
                  v-if="chatMsg.content && chatMsg.content.indexOf('pdf') >= 0"
                  @click="downloadFile(chatMsg.content, chatMsg.fileName)"
                  class="span-download"
                >下载</span>
                <a v-else :href="chatMsg.content" target="_blank" download style="marginLeft: 5px">下载</a>
                <span style="color: #008BEE;cursor:pointer;border-left: 2px solid #ccc;padding-left:8px;display:inline-block;margin-left:8px;line-height:12px" v-preview.delete="[chatMsg.fileName, chatMsg.content]">预览</span>
              </p>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>
<script lang="ts">
import { Component, Vue, Prop } from 'vue-property-decorator'
import webchatBigImage from '@/views/webchat/bigImg/webchatBigImage.vue'
import webchatVoice from '@/views/webchat/common/webchatVoice.vue'
import { WebchatModule } from '@/store/modules/webchat'
import { OutNameObj, MessageObj } from '@/views/webchat/webchatInterface'
import FileSave from 'file-saver';
@Component({
  name: 'webchatMsgItem',
  components: { webchatBigImage, webchatVoice },
  filters: {
    handleTextBoxWidth (chatMsg: MessageObj) { // 处理输入框宽度
      if (
        (chatMsg.type === 'out' &&
        chatMsg.sendStatus &&
        chatMsg.sendStatus !== 'success' &&
        chatMsg.sendStatus !== 'fail' &&
        chatMsg.contentType !== 'file') ||
        chatMsg.errorCode
      ) {
        return 'maxWidth: calc(100% - 40px)'
      } else {
        return ''
      }
    },
    fileIcon (chatMsg: MessageObj) { // 文件icon处理
      const fileExtension = chatMsg.fileName ? chatMsg.fileName.split('.').pop().toLowerCase() : ''
      const audio = ['mp3', 'mpeg', 'midi']
      if (audio.includes(fileExtension)) {
        return 'yinle'
      } else if (fileExtension === 'mp4') {
        return 'shipin'
      } else {
        return 'wenjian'
      }
    }
  }
})
export default class WebchatMsgItem extends Vue {
  @Prop({ default: {} }) private chatMsg!: any
  @Prop() private chatMsgIndex: number | undefined // 当前会话index
  @Prop({ default: {} }) private imageUrls!: any
  @Prop() private messageList: any // 消息历史
  @Prop() private sessionId: string |undefined // 会话Id
  @Prop() private common: any // 座席的公共数据
  @Prop() private importType: string | undefined // 哪个模块引用的
  private $bus: any
  private $store: any
  private $route: any

  private lastPlayTime = 0

  private outName (obj: OutNameObj) {
    if (obj.userId === 'robot') {
      return '机器人'
    } else if (obj.userId === 'system') {
      return '系统'
    } else {
      return obj.userId === this.common.userId ? '我' : obj.userName
    }
  }

  private downloadFile (fileUrl: string, fileName?: string) { // 下载文件
    const oReq: any = new XMLHttpRequest()
    const arr = fileUrl.split('.') // 通过\分隔字符串，成字符串数组
    const fileType = arr[arr.length - 1] // 取最后一个，就是文件类型
    if (!fileName) { // 没有文件名, 就用Url截取下
      const str = fileUrl.lastIndexOf('/') // 取到文件名开始到最后一个/的长度
      fileName = fileUrl.substring(str + 1, fileUrl.length)
    }
    oReq.open('GET', fileUrl, true)
    oReq.responseType = 'blob'
    oReq.onload = () => {
      const file = new Blob([oReq.response], {
        type: `application/${fileType}`
      })
      FileSave.saveAs(file, fileName)
    }
    oReq.send()
  }

  private picUrlHandle (url: string) {
    const reg = /(http|https):\/\/([\w.]+\/?)\S*/
    return reg.test(url) ? url : this.common.doMain + url
  }

  private previewImg (chatMsg: MessageObj) { // 点击图片
    this.$emit('previewImg', chatMsg)
  }

  private toEditFun (withdrawMsg: string, withdrawMsgNew: string) {
    this.$bus.$emit('toEditFun', withdrawMsg, withdrawMsgNew)
  }

  private withdrawFun (chatMsg: MessageObj) { // 消息撤回
    this.$emit('withdrawFun', chatMsg)
  }

  private playVoice (chatMsg: MessageObj) { // 播放语音
    const currentTime = Date.now()
    if ((currentTime - this.lastPlayTime) < 300) {
      return
    }
    const arr = this.$route.path.split('/') || []
    const tabType = arr.length > 4 ? arr[3] : 'webchatDateCenter'
    if (!chatMsg.play) {
      WebchatModule.RESET_CHAT_VOICE_PLAY({ tabType, sessionId: this.sessionId })
      WebchatModule.SET_CHAT_VOICE_PLAY({ tabType, sessionId: this.sessionId, play: true, createTimestamp: chatMsg.createTimestamp })
    } else {
      WebchatModule.SET_CHAT_VOICE_PLAY({ tabType, sessionId: this.sessionId, play: false, createTimestamp: chatMsg.createTimestamp })
    }
    this.lastPlayTime = Date.now()
  }

  private disabledFun (chatMsg: any) { // 是否显示撤回
    const time = new Date().getTime()
    if (!chatMsg.tipDisabled) {
      return false
    } else if (chatMsg.createTimestamp && time - chatMsg.createTimestamp > 180000) {
      chatMsg.tipDisabled = false
    }
  }

  private orderOpen (data: any) {
    if (data.type === 'self' || data.type === 'user') {
      return false
    }
    if (data.type && data.url) {
      window.open(data.url)
    }
  }

  private playVideo (chatMsg: MessageObj) { // 在线播放视频
    const arr = this.$route.path.split('/') || []
    const tabType = arr[3]
    if (tabType === 'webchat_todo') {
      this.$bus.$emit('webchatVideoReplay', { chatMsg })
    } else {
      this.$bus.$emit('webchatDataVideoReplay', { chatMsg })
    }
  }

  private handleRobotSearch () {
    (this.$bus as any).$emit('topSearchHandle', {
      sessionId: this.sessionId,
      content: this.chatMsg.content
    })
  }

  get currentTabType () {
    const arr = this.$route.path.split('/') || []
    if (arr[3]) {
      return arr[3];
    }
  }
}
</script>
<style lang="stylus">
  .webchatMsgItem
    width 100%
    .span-download
      margin-left 5px
      cursor pointer
      color $c-main
    .systemMsg
      text-align center
      width 100%
      .csrSubmit
        color #008BEE
        text-overflow ellipsis
        white-space nowrap
        overflow hidden
        max-width calc(100% - 200px)
        display inline-block
        vertical-align bottom
    .toEdit
      color #008BEE
      cursor pointer
    .historyLine
      margin 20px 0px
      .dividedLine
        width 60px
        display inline-block
        height 1px
        vertical-align middle
        background #E7E9ED
      .historyText
        display inline-block
        margin 0px 20px
    .chatContent
      width calc(100% - 100px)
      .headImg
        width 36px
        height 36px
        border-radius 50%
      .systemHeadImg
        background #E7E9ED
      .visitorsHeadImg
        width 36px
        height 36px
        border-radius 50%
        img
          border-radius 50%
          height 100%
          width 100%
      .inTime
        text-align left
      .outTime
        text-align right
      .time
        margin 0px 5px
        color #767E91
        overflow hidden
        text-overflow ellipsis
        width 80%
        white-space nowrap
        .name
          margin-left 5px
      .msgStatus
        font-size 12px
        position absolute
        top 18px
        left -20px
      .chatContentBox
        max-width calc(100% - 60px)
        border 1px solid #fff
        color $fc-gray2
        margin-top -20px
        position relative
        .chatContentItemBoxSearch:hover
          padding-right: 30px
          .search
            display block
        .chatContentItemBox
          max-width 100%
          line-height 22px
          padding 14px
          word-break break-word
          white-space normal
          position: relative
          transition padding-right .2s ease
          .search
            cursor pointer
            display: none
            transition .2s ease
            right: 6px
            bottom: 13px
            position: absolute
          img
            width 100%
        .V7_iconV7tubiao_chehui
          position absolute
          display none
          cursor pointer
          float left
          top 17px
          left -21px
          background #fff
          color #008BEE
        .outTextBgc
          background-color #EFF0F3
          border-radius 10px
        .inTextBgc
          border-radius 10px
          background #CCE8FC
        .isSearchKey
          background #FFFBE6 !important
        .voiceBgc
          background #008BEE
          opacity 0.03
          border-radius 10px
        .imageMsg
          background-color white
          max-width 100%
        .cardInfo
          padding 14px
          border 1px solid $border-main
          border-radius 10px
          img
            height 68px
            width 68px
            border-radius 4px
            margin-right 14px
          .cardInfoLeft
            width 130px
            .cardInfoTitle
              text-align left
              line-height 1.5em
              color #303753
              text-overflow ellipsis
              display -webkit-box
              -webkit-line-clamp 2
              -webkit-box-orient vertical
              overflow hidden
              margin-bottom 14px
            .cardInfoFlag
              color #767E91
              padding-top 10px
              border-top 1px solid $border-main
              .V7_iconV7tubiao_weixinxiaochengxu
                color #7587D8
                visibility middle
        .orderCardInfo
          padding 13px 16px
          border 1px solid $border-main
          border-radius 10px
          .orderNum
            padding 6px 0px
            border-bottom 1px solid $border-main
            color #767E91
            span
              margin-right 4px
          .orderListItem
            margin-top 6px
            cursor pointer
            img
              width 52px
              height 52px
              border 1px solid $border-main
              border-radius 4px
            .orderRight
              width 190px
              margin-left 10px
              .orderRightTitle
                text-align left
                line-height 1.5em
                color #303753
                text-overflow ellipsis
                display -webkit-box
                -webkit-line-clamp 2
                -webkit-box-orient vertical
                overflow hidden
                margin-bottom 6px
              .orderPrice
                color #FC6B5C
          .orderBtn
            width 70px
            height 24px
            line-height 24px
            text-align center
            border 1px solid $border-main
            border-radius 12px
            margin-top 15px
            cursor pointer
        .videoBox
          max-width 200px
          max-height 200px
          position relative
          cursor pointer
          img
            border-radius 10px
            max-height 200px
        .videoBoxNoData
          border-radius 10px
          height 150px
          width 200px
          background-color #b7b7b7
        .fileMsg
          background-color white
          border 1px solid $border-main
          padding 0px 10px 10px 16px
          border-radius 10px
          width 300px
          position relative
          .fileProess
            background #008BEE
            opacity 0.1
            height 60px
            position absolute
            top 0px
            border-radius 10px 0px 0px 10px
            left 0
          .fileIcon
            display inline-block
            font-size 36px
            text-align center
            border-radius 4px
            margin 10px 11px 0px 0px
          .V7_iconV7tubiao_yinle
            color #53B192
          .V7_iconV7tubiao_shipin
            color #BF6CF7
          .fileName
            font-size 14px
            color #303753
            margin-top 10px
            width 200px
            text-overflow ellipsis
            overflow hidden
            white-space nowrap
          .fileSize
            color #767E91
      .inBox
        margin-left 40px
      .outBox
        margin-right 40px
      .sendStatus
        display inline-block
        background url(../../assets/img/webchat_send.gif) no-repeat
        background-size 20px 20px
        margin 10px
        width 20px
        height 20px
      .sendStatus.success
        display none
      .sendStatus.fail
        display inline-block
        background url(../../assets/img/reply_error.png) no-repeat
        background-size 20px 20px
      .wechat_video_play_icon
        position absolute
        width 100%
        height 100%
      .play_icon
        position absolute
        width 26px
        height 26px
        margin -13px 0 0 -13px
        top 50%
        left 50%
        background url('../../assets/img/play_icon.png') no-repeat
        z-index 2
    .chatContent:hover
      .V7_iconV7tubiao_chehui
        display block
        z-index 100
</style>
